package live.ifox.factory;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import live.ifox.helper.CommonHelper;

public class PermissionInfo {
    private static final String fileName = "permission.json";
    public static final String Url = "https://developer.android.google.cn/reference/android/Manifest.permission";

    private List<Map<String, Object>> infoModel;
    private Context mContext;

    public PermissionInfo(Context context) {
        this.mContext = context;
        infoModel = new ArrayList<>();
    }

    private void addItem(String label, Object detail) {
        Map<String, Object> map = new HashMap<>();
        map.put("label", label);
        map.put("detail", detail);
        infoModel.add(map);
    }

    private String readFromAssets() {
        StringBuilder result = new StringBuilder();
        try {
            InputStreamReader inputReader = new InputStreamReader(mContext.getAssets().open(fileName));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            while ((line = bufReader.readLine()) != null)
                result.append(line);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    public List<Map<String, Object>> getModel() {
        String result = readFromAssets();
        try {
            JSONObject rootObject = JSON.parseObject(result);
            JSONArray array = rootObject.getJSONArray("items");
            for (int i = 0; i < array.size(); i++) {
                JSONObject item = array.getJSONObject(i);
                addItem(item.getString("label"), item.get("detail"));
            }
        } catch (JSONException e) {
            CommonHelper.debug("ERROR: 错误的JSON格式！");
        }
        return infoModel;
    }
}
